﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Xyz.Core.Interfaces;
using Xyz.Core.Models;
using Xyz.Core.Models.Filters;
using Xyz.Core.Web.Filters;
using Xyz.Core.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Xyz.Core.Infrastructure.Extentions;
using Microsoft.AspNetCore.Authorization;
using System;

namespace Xyz.Core.Web.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    [Authorize]
    public class UserController : Controller
    {
        private readonly IUserService _userService;
        private readonly IRoleService _roleService;
        private readonly IMapper _mapper;

        public UserController(IUserService userSvc, IRoleService roleSvc, IMapper mapper)
        {
            _userService = userSvc;
            _roleService = roleSvc;
            _mapper = mapper;
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 用户角色授权
        /// </summary>
        /// <returns></returns>
        public IActionResult Authen(Guid id)
        {
            var user = new UserDto
            {
                Id = id
            };
            return View(user);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            return View(new UserAddDto());
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(Guid id)
        {
            var dto = await _userService.FindAsync(id);
            var model = _mapper.Map<UserDto, UserUpdateDto>(dto);
            return View(model);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Add(UserAddDto dto)
        {
            if (ModelState.IsValid)
            {
                var result = await _userService.AddAsync(dto);
                if (result != Guid.Empty)
                    return RedirectToAction("Index");
            }
            return View(dto);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(UserUpdateDto dto)
        {
            if (ModelState.IsValid)
            {
                var result = await _userService.UpdateAsync(dto);
                if (result)
                    return RedirectToAction("Index");
            }
            return View(dto);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<IActionResult> Delete([FromBody]List<Guid> ids)
        {
            var result = new JsonResultModel<bool>();
            if (ids.AnyOne())
            {
                result.flag = await _userService.DeleteAsync(ids);
            }
            return Json(result);
        }

        /// <summary>
        /// 搜索页面
        /// </summary>
        /// <param name="filters">查询参数</param>
        /// <returns></returns>
        [IgnoreRightFilter]
        public async Task<IActionResult> GetListWithPager(UserFilters filters)
        {
            var result = await _userService.SearchAsync(filters);
            return Json(result);
        }

        /// <summary>
        /// 我的角色
        /// </summary>
        /// <param name="filters">查询参数</param>
        /// <returns></returns>
        [IgnoreRightFilter]
        public async Task<IActionResult> GetMyRoles(RoleFilters filters)
        {
            var result = await _roleService.SearchAsync(filters);
            return Json(result);
        }

        /// <summary>
        /// 我尚未拥有的角色
        /// </summary>
        /// <param name="filters">查询参数</param>
        /// <returns></returns>
        [IgnoreRightFilter]
        public async Task<IActionResult> GetNotMyRoles(RoleFilters filters)
        {
            filters.ExcludeMyRoles = true;
            var result = await _roleService.SearchAsync(filters);
            return Json(result);
        }

        /// <summary>
        /// 用户角色授权
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GiveRight(Guid id, Guid userId)
        {
            var result = new JsonResultModel<bool>
            {
                flag = await _userService.GiveAsync(userId, id)
            };
            return Json(result);
        }

        /// <summary>
        /// 用户角色取消
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CancelRight(Guid id, Guid userId)
        {
            var result = new JsonResultModel<bool>
            {
                flag = await _userService.CancelAsync(userId, id)
            };
            return Json(result);
        }

        /// <summary>
        /// 验证登录名是否重复
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns></returns>
        [HttpGet]
        [IgnoreRightFilter]
        public async Task<IActionResult> VerifyLoginName(string loginName)
        {
            var isExists = await _userService.ExistsLoginNameAsync(null, loginName);
            return isExists ? Json("登录帐号已存在") : Json(data: true);
        }
    }
}